package edu.dayu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class TxtJsonArr {
    public static void main(String[] args) {
        String filepath = "C:\\Users\\86134\\Desktop\\1111.txt";
        readFile(filepath);
    }

    /**
     * 读取txt文件，返回json字符串
     * @param filePath
     * @return
     */
    public static void readFile(String filePath){
        List<String> list = new ArrayList<>();
        try {
            FileReader fileReader = new FileReader(filePath);
            BufferedReader reader = new BufferedReader(fileReader);
            FileWriter fileWriter = new FileWriter("C:\\Users\\86134\\Desktop\\test.txt");
            BufferedWriter writer = new BufferedWriter(fileWriter);
            String line;
            while((line = reader.readLine()) != null){
                list.add(transfer(line));
            }
            System.out.println(list.size());
            writer.write(list.toString());
            reader.close();
            writer.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 将一行数据转化为json字符串
     * @param line
     * @return
     */
    public static String transfer(String line){
        String[] split = line.split(",");
        Map<String,String> map = new LinkedHashMap<>();
        //meterNo，instanFlow，meterReading，battery，pressure，readTime，signal
        map.put("meterNo",split[0]);
        map.put("instanFlow",split[1]);
        map.put("meterReading",split[2]);
        map.put("battery",split[3]);
        map.put("pressure",split[4]);
        map.put("readTime",split[5]);
        map.put("signal",split[6]);
        String json = JSONArray.toJSONString(map);;
        return json;
    }

}
